
<!DOCTYPE HTML>
<html lang="" >
    <head>
        <meta charset="UTF-8">
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <title>其他 · GitBook</title>
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="description" content="">
        <meta name="generator" content="GitBook 3.2.2">
        
        
        
    
    <link rel="stylesheet" href="../gitbook/style.css">

    
            
                
                <link rel="stylesheet" href="../gitbook/gitbook-plugin-highlight/website.css">
                
            
                
                <link rel="stylesheet" href="../gitbook/gitbook-plugin-search/search.css">
                
            
                
                <link rel="stylesheet" href="../gitbook/gitbook-plugin-fontsettings/website.css">
                
            
        

    

    
        
    
        
    
        
    
        
    
        
    
        
    

        
    
    
    <meta name="HandheldFriendly" content="true"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <link rel="apple-touch-icon-precomposed" sizes="152x152" href="../gitbook/images/apple-touch-icon-precomposed-152.png">
    <link rel="shortcut icon" href="../gitbook/images/favicon.ico" type="image/x-icon">

    
    <link rel="next" href="../collections.html" />
    
    
    <link rel="prev" href="thread-local.html" />
    

    </head>
    <body>
        
<div class="book">
    <div class="book-summary">
        
            
<div id="book-search-input" role="search">
    <input type="text" placeholder="Type to search" />
</div>

            
                <nav role="navigation">
                


<ul class="summary">
    
    

    

    
        
        <li class="header">Java</li>
        
        
    
        <li class="chapter " data-level="1.1" data-path="../">
            
                <a href="../">
            
                    
                    Introduction
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.2" data-path="../object-mgmr.html">
            
                <a href="../object-mgmr.html">
            
                    
                    对象管理
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.3" data-path="../enum.html">
            
                <a href="../enum.html">
            
                    
                    枚举
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4" data-path="../object-common.html">
            
                <a href="../object-common.html">
            
                    
                    对象通用行为
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5" data-path="../concurrent.html">
            
                <a href="../concurrent.html">
            
                    
                    线程和并发
            
                </a>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="1.5.1" data-path="how-to.html">
            
                <a href="how-to.html">
            
                    
                    线程和线程池
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.2" data-path="block-close.html">
            
                <a href="block-close.html">
            
                    
                    线程阻塞和关闭
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.3" data-path="communicate.html">
            
                <a href="communicate.html">
            
                    
                    线程协作
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.4" data-path="volatile.html">
            
                <a href="volatile.html">
            
                    
                    活性失败-volatile
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.5" data-path="lock.html">
            
                <a href="lock.html">
            
                    
                    安全性失败-锁
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.6" data-path="thread-local.html">
            
                <a href="thread-local.html">
            
                    
                    线程局部存储
            
                </a>
            

            
        </li>
    
        <li class="chapter active" data-level="1.5.7" data-path="others.html">
            
                <a href="others.html">
            
                    
                    其他
            
                </a>
            

            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="1.6" data-path="../collections.html">
            
                <a href="../collections.html">
            
                    
                    集合
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.7" data-path="../nio.html">
            
                <a href="../nio.html">
            
                    
                    nio
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.8" data-path="../advance.html">
            
                <a href="../advance.html">
            
                    
                    泛型，注解和反射
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.9" data-path="../mem-gc.html">
            
                <a href="../mem-gc.html">
            
                    
                    内存模型和GC
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.10" data-path="../classloader.html">
            
                <a href="../classloader.html">
            
                    
                    ClassLoader
            
                </a>
            

            
        </li>
    

    
        
        <li class="header">Web</li>
        
        
    
        <li class="chapter " data-level="2.1" data-path="../spring.html">
            
                <a href="../spring.html">
            
                    
                    spring
            
                </a>
            

            
        </li>
    

    
        
        <li class="header">GUI</li>
        
        
    
        <li class="chapter " data-level="3.1" data-path="../gui-1.html">
            
                <a href="../gui-1.html">
            
                    
                    没事写个小界面什么的
            
                </a>
            

            
        </li>
    

    

    <li class="divider"></li>

    <li>
        <a href="https://www.gitbook.com" target="blank" class="gitbook-link">
            Published with GitBook
        </a>
    </li>
</ul>


                </nav>
            
        
    </div>

    <div class="book-body">
        
            <div class="body-inner">
                
                    

<div class="book-header" role="navigation">
    

    <!-- Title -->
    <h1>
        <i class="fa fa-circle-o-notch fa-spin"></i>
        <a href=".." >其他</a>
    </h1>
</div>




                    <div class="page-wrapper" tabindex="-1" role="main">
                        <div class="page-inner">
                            
<div id="book-search-results">
    <div class="search-noresults">
    
                                <section class="normal markdown-section">
                                
                                <h1 id="&#x5176;&#x4ED6;">&#x5176;&#x4ED6;</h1>
<p>#</p>
<h2 id="3-invokeall&#x548C;invokeany">3 invokeAll&#x548C;invokeAny</h2>
<p>&#x770B;&#x65B9;&#x6CD5;doInvkeAny&#xFF0C;&#x5927;&#x4F53;&#x5957;&#x8DEF;&#x662F;&#xFF1A;</p>
<pre><code>T doInvkeAny(Collection&lt;Callable&lt;T&gt;&gt; tasks, boolean timed, long nanos){

    int ntasks = tasks.size();
    ArrayList&lt;Future&lt;T&gt;&gt; futures = new ArrayList&lt;Future&lt;T&gt;&gt;(ntasks);

    ExecutorCompletionService&lt;T&gt; ecs = new ExecutorCompletionService&lt;T&gt;(this);
    Iterator&lt;? extends Callable&lt;T&gt;&gt; it = tasks.iterator();

    &#x540E;&#x9762;&#x8FD8;&#x6709;&#xFF0C;&#x6CA1;&#x6574;&#x660E;&#x767D;&#x662F;&#x600E;&#x4E48;&#x6DFB;&#x52A0;&#x7684;&#x4EFB;&#x52A1;
}
</code></pre><p>&#x6D89;&#x53CA;&#x5230;&#x4E86;ExecutorCompletionService&#xFF0C;CompletionService&#xFF0C;LinkedBlockingQueue&#x7B49;&#x7B49;</p>
<p>&#x8FD9;&#x90E8;&#x5206;&#x662F;&#x5E72;&#x4EC0;&#x4E48;&#x7684;&#x90FD;&#x6CA1;&#x6574;&#x660E;&#x767D;</p>
<pre><code>
private &lt;T&gt; T doInvokeAny(Collection&lt;? extends Callable&lt;T&gt;&gt; tasks,
                              boolean timed, long nanos)
    throws InterruptedException, ExecutionException, TimeoutException {
    if (tasks == null)
        throw new NullPointerException();
    int ntasks = tasks.size();
    if (ntasks == 0)
        throw new IllegalArgumentException();
    ArrayList&lt;Future&lt;T&gt;&gt; futures = new ArrayList&lt;Future&lt;T&gt;&gt;(ntasks);
    ExecutorCompletionService&lt;T&gt; ecs =
        new ExecutorCompletionService&lt;T&gt;(this);

    // For efficiency, especially in executors with limited
    // parallelism, check to see if previously submitted tasks are
    // done before submitting more of them. This interleaving
    // plus the exception mechanics account for messiness of main
    // loop.

    try {
        // Record exceptions so that if we fail to obtain any
        // result, we can throw the last exception we got.
        ExecutionException ee = null;
        final long deadline = timed ? System.nanoTime() + nanos : 0L;
        Iterator&lt;? extends Callable&lt;T&gt;&gt; it = tasks.iterator();

        // Start one task for sure; the rest incrementally
        futures.add(ecs.submit(it.next()));
        --ntasks;
        int active = 1;

        for (;;) {
            Future&lt;T&gt; f = ecs.poll();
            if (f == null) {
                if (ntasks &gt; 0) {
                    --ntasks;
                    futures.add(ecs.submit(it.next()));
                    ++active;
                }
                else if (active == 0)
                    break;
                else if (timed) {
                    f = ecs.poll(nanos, TimeUnit.NANOSECONDS);
                    if (f == null)
                        throw new TimeoutException();
                    nanos = deadline - System.nanoTime();
                }
                else
                    f = ecs.take();
            }
            if (f != null) {
                --active;
                try {
                    return f.get();
                } catch (ExecutionException eex) {
                    ee = eex;
                } catch (RuntimeException rex) {
                    ee = new ExecutionException(rex);
                }
            }
        }

        if (ee == null)
            ee = new ExecutionException();
        throw ee;

    } finally {
        for (int i = 0, size = futures.size(); i &lt; size; i++)
            futures.get(i).cancel(true);
    }
}
</code></pre><h2 id="4-&#x5173;&#x4E8E;executorcompletionservice&#xFF0C;completionservice">4 &#x5173;&#x4E8E;ExecutorCompletionService&#xFF0C;CompletionService</h2>
<p>&#x5B9E;&#x73B0;&#x4E86;CompletionService&#xFF0C;&#x5C06;&#x6267;&#x884C;&#x5B8C;&#x6210;&#x7684;&#x4EFB;&#x52A1;&#x653E;&#x5230;&#x963B;&#x585E;&#x961F;&#x5217;&#x4E2D;&#xFF0C;&#x901A;&#x8FC7;take&#x6216;poll&#x65B9;&#x6CD5;&#x6765;&#x83B7;&#x5F97;&#x6267;&#x884C;&#x7ED3;&#x679C;</p>
<pre><code>///&#x4F8B;4&#xFF1A;&#xFF08;&#x542F;&#x52A8;10&#x6761;&#x7EBF;&#x7A0B;&#xFF0C;&#x8C01;&#x5148;&#x6267;&#x884C;&#x5B8C;&#x6210;&#x5C31;&#x8FD4;&#x56DE;&#x8C01;&#xFF09;
public class CompletionServiceTest {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executor = Executors.newFixedThreadPool(10);        //&#x521B;&#x5EFA;&#x542B;10&#x6761;&#x7EBF;&#x7A0B;&#x7684;&#x7EBF;&#x7A0B;&#x6C60;
        CompletionService completionService = new ExecutorCompletionService(executor);
        for (int i =1; i &lt;=10; i ++) {
            final  int result = i;
            completionService.submit(new Callable() {
                public Object call() throws Exception {
                    Thread.sleep(new Random().nextInt(5000));   //&#x8BA9;&#x5F53;&#x524D;&#x7EBF;&#x7A0B;&#x968F;&#x673A;&#x4F11;&#x7720;&#x4E00;&#x6BB5;&#x65F6;&#x95F4;
                    return result;
                }
            });
        }
        System.out.println(completionService.take().get());   //&#x83B7;&#x53D6;&#x6267;&#x884C;&#x7ED3;&#x679C;
    }
}
//&#x8F93;&#x51FA;&#x7ED3;&#x679C;&#x53EF;&#x80FD;&#x6BCF;&#x6B21;&#x90FD;&#x4E0D;&#x540C;&#xFF08;&#x5728;1&#x5230;10&#x4E4B;&#x95F4;&#xFF09;
</code></pre><h1 id="&#x7B2C;&#x4E94;&#x8BFE;&#xFF1A;">&#x7B2C;&#x4E94;&#x8BFE;&#xFF1A;</h1>

                                
                                </section>
                            
    </div>
    <div class="search-results">
        <div class="has-results">
            
            <h1 class="search-results-title"><span class='search-results-count'></span> results matching "<span class='search-query'></span>"</h1>
            <ul class="search-results-list"></ul>
            
        </div>
        <div class="no-results">
            
            <h1 class="search-results-title">No results matching "<span class='search-query'></span>"</h1>
            
        </div>
    </div>
</div>

                        </div>
                    </div>
                
            </div>

            
                
                <a href="thread-local.html" class="navigation navigation-prev " aria-label="Previous page: 线程局部存储">
                    <i class="fa fa-angle-left"></i>
                </a>
                
                
                <a href="../collections.html" class="navigation navigation-next " aria-label="Next page: 集合">
                    <i class="fa fa-angle-right"></i>
                </a>
                
            
        
    </div>

    <script>
        var gitbook = gitbook || [];
        gitbook.push(function() {
            gitbook.page.hasChanged({"page":{"title":"其他","level":"1.5.7","depth":2,"next":{"title":"集合","level":"1.6","depth":1,"path":"collections.md","ref":"collections.md","articles":[]},"previous":{"title":"线程局部存储","level":"1.5.6","depth":2,"path":"concurrent/thread-local.md","ref":"concurrent/thread-local.md","articles":[]},"dir":"ltr"},"config":{"gitbook":"*","theme":"default","variables":{},"plugins":[],"pluginsConfig":{"highlight":{},"search":{},"lunr":{"maxIndexSize":1000000,"ignoreSpecialCharacters":false},"sharing":{"facebook":true,"twitter":true,"google":false,"weibo":false,"instapaper":false,"vk":false,"all":["facebook","google","twitter","weibo","instapaper"]},"fontsettings":{"theme":"white","family":"sans","size":2},"theme-default":{"styles":{"website":"styles/website.css","pdf":"styles/pdf.css","epub":"styles/epub.css","mobi":"styles/mobi.css","ebook":"styles/ebook.css","print":"styles/print.css"},"showLevel":false}},"structure":{"langs":"LANGS.md","readme":"README.md","glossary":"GLOSSARY.md","summary":"SUMMARY.md"},"pdf":{"pageNumbers":true,"fontSize":12,"fontFamily":"Arial","paperSize":"a4","chapterMark":"pagebreak","pageBreaksBefore":"/","margin":{"right":62,"left":62,"top":56,"bottom":56}},"styles":{"website":"styles/website.css","pdf":"styles/pdf.css","epub":"styles/epub.css","mobi":"styles/mobi.css","ebook":"styles/ebook.css","print":"styles/print.css"}},"file":{"path":"concurrent/others.md","mtime":"2017-04-09T06:00:56.640Z","type":"markdown"},"gitbook":{"version":"3.2.2","time":"2017-04-09T09:50:22.406Z"},"basePath":"..","book":{"language":""}});
        });
    </script>
</div>

        
    <script src="../gitbook/gitbook.js"></script>
    <script src="../gitbook/theme.js"></script>
    
        
        <script src="../gitbook/gitbook-plugin-search/search-engine.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-search/search.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-lunr/lunr.min.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-lunr/search-lunr.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-sharing/buttons.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-fontsettings/fontsettings.js"></script>
        
    

    </body>
</html>

